<template>
  <div class="contract-detail route-page" :class="isMobile ? 'isMobile' : ''">
    <section class="header">
      <!--  @back="goBack" -->
      <a-page-header :class="notBack ? 'hide-back' : ''" :title="headerInfo.pageTitle"
                     @back="goBack">
        <template #backIcon>
          <ArrowLeftOutlined v-if="showType !== 'drawer'"/>
        </template>
        <template #tags>
          <template v-if="headerInfo.is_formal == 1">
            <a-tag color="green">已转正式合同</a-tag>
          </template>
          <template v-else>
            <a-tag
                :color="headerInfo.statusColor"
                v-if="headerInfo.statusText"
            >{{ headerInfo.statusText }}
            </a-tag
            >
            <a-tag color="blue" v-if="headerInfo.is_renewal == 1">已续租</a-tag>
            <a-tag color="purple" v-if="headerInfo.hasChanged">已变更</a-tag>
          </template>
        </template>
        <template #extra>
          <!--'APPROVE ' 'RETREAT', 'CHANGE', 'CANCEL', 'CONTINUE', 'DELETE', 'EDIT' 'REVOKE' 'ESIGN'  'LOOK_RETREAT_AGREE'  'CHANGE'  'COPY' 'LOOK_NEW'  'CHANGE_FORMAL'-->
          <!--审批\退租\变更\作废\续租\删除\编辑\撤销申请\电子签约 \查看退租协议\变更\复制\查看新合同\意向合同转正-->
          <!-- '新建待审核' => self::CONTRACT_STATUS_1,
          '正常执行中' => self::CONTRACT_STATUS_2,
          '变更待审批' => self::CONTRACT_STATUS_3,
          '变更待修改' => self::CONTRACT_STATUS_4,
          '退租待审批' => self::CONTRACT_STATUS_5,
          '退租待执行' => self::CONTRACT_STATUS_6,
          '已退租' => self::CONTRACT_STATUS_7,
          '作废待审批' => self::CONTRACT_STATUS_8,
          '作废待修改' => self::CONTRACT_STATUS_9,
          '到期未处理' => self::CONTRACT_STATUS_10,
          '已驳回' => self::CONTRACT_STATUS_11,
          '已作废' => self::CONTRACT_STATUS_12,
          '已撤销' => self::CONTRACT_STATUS_13,
          '待执行' => self::CONTRACT_STATUS_14, -->
          <div style="display: flex">
            <!-- <a-col
              v-if="
                (headerInfo.op_type == 1 && headerInfo.status == 10) ||
                headerInfo.status == 14 ||
                headerInfo.status == 2
              "
              style="margin-right: 20px"
            >
              <a-select
                v-model:value="selectValue"
                :options="selectoptions"
                @change="handleChange"
                :disabled="headerInfo.is_renewal == 1"
              >
              </a-select>
            </a-col> -->
            <a-row
                :gutter="12"
                v-if="headerInfo.btns && headerInfo.btns.length"
            >
              <!-- <a-col v-if="headerInfo.btns.includes('CHANGE')">
                <a-button
                  v-permission="['contractList', 'auth', 'contractChange']"
                  key="CHANGE"
                  @click="handleTopBtnClick('change')"
                >
                  变更
                </a-button>
              </a-col> -->
              <a-col v-if="headerInfo.btns.includes('TRANSFER')">
                <a-button key="TRANSFER" type="primary" ghost
                          @click="handleTopBtnClick('TRANSFER')">
                  结转
                  <text-tip
                      :tips="['在不产生新流水的情况下，可以将收款和退款金额进行抵冲，达到平账目的。']"
                  />
                </a-button>
              </a-col>
              <a-col v-if="headerInfo.btns.includes('ONHANDLEBILL')">
                <a-button key="ONHANDLEBILL" type="primary" ghost
                          @click="handleTopBtnClick('ONHANDLEBILL')">
                  查看待处理账单
                </a-button>
              </a-col>
              <a-col v-if="headerInfo.btns.includes('LOOK_NEW')">
                <a-button key="LOOK_NEW" @click="handleTopBtnClick('LOOK_NEW')">
                  查看新合同
                </a-button>
              </a-col>
              <a-col v-if="headerInfo.btns.includes('ESIGN')">
                <a-button
                    v-permission="['contractList', 'auth', 'contractEsign']"
                    type="primary"
                    key="ESIGN"
                    @click="handleTopBtnClick('esign')"
                >
                  电子签约
                </a-button>
              </a-col>
              <a-col v-if="contractBasicInfo.sign_url">
                <a-button
                    type="primary"
                    key="ESIGNCHECK"
                    @click="handleTopBtnClick('esignCheck')"
                >
                  查看电子合同
                </a-button>
              </a-col>
              <a-col v-if="headerInfo.btns.includes('APPROVE')">
                <a-button
                    v-permission="['contractList', 'auth', 'approveDetail']"
                    type="primary"
                    key="APPROVE"
                    @click="handleTopBtnClick('approval')"
                >
                  查看审批
                </a-button>
              </a-col>
              <a-col v-if="headerInfo.btns.includes('REVOKE')">
                <a-button
                    danger
                    key="REVOKE"
                    @click="handleTopBtnClick('revoke')"
                    v-permission="['contractList', 'auth', 'toRevoke']"
                >
                  撤销申请
                </a-button>
              </a-col>
              <a-col v-if="headerInfo.btns.includes('EDIT')">
                <a-button
                    type="primary"
                    ghost
                    key="EDIT"
                    @click="handleTopBtnClick('edit')"
                >
                  编辑
                </a-button>
              </a-col>
              <!-- <a-button
            type="primary"
            ghost
            key="CHANGE"
            v-if="headerInfo.btns.includes('CHANGE')"
            >变更</a-button
          > -->
              <a-col v-if="headerInfo.btns.includes('RETREAT')">
                <a-button
                    type="primary"
                    danger
                    ghost
                    key="RETREAT"
                    @click="handleTopBtnClick('retreat')"
                    v-permission="['contractList', 'auth', 'contractRetreat']"
                >
                  退租
                </a-button>
              </a-col>
              <a-col v-if="headerInfo.btns.includes('CONTINUE')">
                <a-button
                    type="primary"
                    ghost
                    key="CONTINUE"
                    @click="handleTopBtnClick('continue')"
                    v-permission="[
                    contractBasicInfo.op_type == 1
                      ? 'contractList'
                      : 'contractFile',
                    'auth',
                    'contractContinue',
                  ]"
                >
                  续租
                </a-button>
              </a-col>
              <a-col v-if="headerInfo.btns.includes('CHANGE_FORMAL')">
                <a-button
                    type="primary"
                    key="CHANGE_FORMAL"
                    @click="handleTopBtnClick('CHANGE_FORMAL')"
                    v-permission="['contractList', 'auth', 'toVoid']"
                >
                  转正式合同
                </a-button>
              </a-col>
              <a-col v-if="headerInfo.btns.includes('PURPOSE_CHANGE')">
                <a-button
                    type="primary"
                    key="PURPOSE_CHANGE"
                    @click="handleTopBtnClick('PURPOSE_CHANGE')"
                    v-permission="['purposeContractList', 'curd', 'change']"
                >
                  变更
                </a-button>
              </a-col>
              <a-col v-if="headerInfo.btns.includes('PURPOSE_EDIT')">
                <a-button
                    type="primary"
                    key="PURPOSE_EDIT"
                    @click="handleTopBtnClick('PURPOSE_EDIT')"
                >
                  编辑
                </a-button>
              </a-col>
              <a-col v-if="headerInfo.btns.includes('CANCEL')">
                <a-button
                    type="primary"
                    danger
                    key="CANCEL"
                    @click="handleTopBtnClick('cancel')"
                    v-permission="['contractList', 'auth', 'toVoid']"
                >
                  作废
                </a-button>
              </a-col>
              <a-col v-if="headerInfo.btns.includes('DELETE')">
                <a-button
                    type="primary"
                    danger
                    ghost
                    key="DELETE"
                    @click="contractDel"
                >
                  删除
                </a-button>
              </a-col>
              <a-col v-if="headerInfo.btns.includes('LOOK_RETREAT_AGREE')">
                <a-button
                    type="primary"
                    ghost
                    key="retreatHistory"
                    @click="handleTopBtnClick('retreatHistory')"
                    v-permission="[
                    contractBasicInfo.op_type == 1
                      ? 'contractList'
                      : 'contractFile',
                    'auth',
                    'getRetreatAgree',
                  ]"
                >
                  查看退租协议
                </a-button>
              </a-col>
              <a-dropdown
                  v-if="
                  headerInfo.btns.includes('CHANGE') ||
                  headerInfo.btns.includes('COPY')
                "
              >
                <template #overlay>
                  <a-menu @click="handleMenuClick">
                    <a-menu-item
                        key="CHANGE"
                        v-if="headerInfo.btns.includes('CHANGE')"
                        v-permission="['contractList', 'auth', 'contractChange']"
                    >
                      变更
                    </a-menu-item>
                    <a-menu-item
                        key="COPY"
                        v-if="headerInfo.btns.includes('COPY')"
                        v-permission="['contractList', 'auth', 'contractChange']"
                    >
                      复制
                    </a-menu-item>
                  </a-menu>
                </template>
                <a-button type="primary" ghost>
                  更多
                  <DownOutlined/>
                </a-button>
              </a-dropdown>
            </a-row>
          </div>
        </template>
        <template #footer>
          <a-tabs v-model:activeKey="activeTabKey" size="small">
            <a-tab-pane
                v-for="(item, key) in tabList"
                :key="key"
                :tab="item.title"
            />
          </a-tabs>
        </template>
        <a-alert showIcon :message="getHeaderMsg('abstract')" type="info"/>
        <a-alert
            showIcon
            type="info"
            class="mt-10"
            v-if="$store.getters.latestRemark"
        >
          <template #message>
            最新备注：{{ $store.getters.latestRemark }}
          </template>
        </a-alert>
        <a-alert
            showIcon
            type="info"
            class="mt-10"
            v-if="
            contractBasicInfo.voidLog &&
            contractBasicInfo.voidLog.operate_content
          "
        >
          <template #message>
            作废原因：{{
              contractBasicInfo.voidLog.operate_content.content
                  ? contractBasicInfo.voidLog.operate_content.content
                  : "-"
            }}
          </template>
        </a-alert>
        <!-- 只有退租待执行 和 已退租 时才显示退租摘要 -->
        <template v-if="headerInfo.status == 6 || headerInfo.status == 7">
          <a-alert
              showIcon
              type="info"
              class="mt-10"
              v-if="$store.getters.contractRetreatAbstract"
          >
            <template #message>
              退租摘要：{{ $store.getters.contractRetreatAbstract }}
            </template>
          </a-alert>
        </template>
      </a-page-header>
    </section>
    <section class="content">
      <basic-info
          v-show="'basicInfo' == activeTabKey"
          :active="'basicInfo' == activeTabKey"
          :showType="showType"
          :drawerId="contractId"
          :refresh="basicInfoRefresh"
          :discountType="discountType"
      />
      <clause-detail
          v-show="'clauseDetail' == activeTabKey"
          :active="'clauseDetail' == activeTabKey"
          :showType="showType"
          :drawerId="contractId"
      />
      <AnalyzeDetail
          v-show="'analyzeDetail' == activeTabKey"
          :active="'analyzeDetail' == activeTabKey"
          :showType="showType"
          :drawerId="contractId"
      />
      <CarryForwardList
          v-show="'carryForwardList' == activeTabKey"
          :active="'carryForwardList' == activeTabKey"
          :showType="showType"
          :drawerId="contractId"
          @closeAllModal="closeAllModal"
      />
      <section v-show="'contractText' == activeTabKey">
        <a-card
            v-if="contractBasicInfo.apply_contract"
            style="margin-bottom: 10px"
            title="合同模板"
        >
          <a-button type="link" @click="downloadFile">
            {{ contractBasicInfo.apply_contract.contractName }}
          </a-button
          >
        </a-card>
        <attachment-info
            :active="'contractText' == activeTabKey"
            :params="attachParams"
            :showType="showType"
            :drawerId="contractId"
        />
      </section>

      <contract-history
          v-show="'contractHistory' == activeTabKey"
          :active="'contractHistory' == activeTabKey"
          :showType="showType"
          :drawerId="contractId"
      />
      <income-list
          v-show="'incomeList' == activeTabKey"
          :active="'incomeList' == activeTabKey"
      />
      <bill-info
          v-show="'billInfo' == activeTabKey"
          :active="'billInfo' == activeTabKey"
      />
    </section>
  </div>
  <!-- 作废原因 -->
  <a-modal
      v-model:visible="showContentInput"
      :title="contentTitle"
      @ok="handleContentSubmit"
      :centered="true"
  >
    <a-textarea
        v-model:value="contentInput"
        :placeholder="'请输入' + contentTitle"
        :auto-size="{ minRows: 6 }"
    />

    <div style="margin-top: 12px" v-if="contractBasicInfo.op_type !== 5">
      <a-row v-if="topBtnType == 'cancel'" :gutter="[0, 12]">
        <a-col :span="24">
          <a-checkbox v-model:checked="voidOption.option_1">
            同时作废所有关联账单、发票、收据并取绑所有流水
          </a-checkbox>
        </a-col>
        <a-col :span="24">
          <a-checkbox v-model:checked="voidOption.option_2">
            自动关闭账单绑定的流水
          </a-checkbox>
        </a-col>
      </a-row>
    </div>
  </a-modal>
  <!-- 发起电签 loading -->
  <div class="el-loading" v-if="elSignLoading">
    <a-spin tip="发起电子签约中，请稍加等待..."/>
  </div>
  <!-- 续租 -->
  <renewal-lease
      :visible="renewalVisible"
      @cancel="renewalVisible = false"
      @closeAllModal="closeAllModal"
  />

  <add-change
      :visible="changeVisible"
      :id="showType === 'drawer' ? contractId : $route.query.id"
      :disabledTime="[
      contractBasicInfo.lease_starttime,
      contractBasicInfo.lease_endtime,
    ]"
      @cancel="changeVisible = false"
  />

  <!-- 电子合同 -->
  <electronContractModal
      :visible="electronContractVisible"
      :contractBasicInfo="contractBasicInfo"
      :esignDetail="esignDetail"
      @close="electronContractVisible = false"
      @refresh="refreshClose"
      type="contractDetail"
      :title="contractTitle"
      :urlData="previewUrlData"
      :showType="showType"
      :drawerId="contractId"
  />

  <!-- 租客审批详情 -->
  <NoHistoryIframe
      title="审批详情"
      :visible="iframeVisible"
      :url="iframeUrl"
      @cancel="iframeModalClose"
  />

  <!-- 待处理账单  -->
  <PendingBillDrawer
      :id="contractBasicInfo.id"
      :visible="pendingBillVisible"
      @handleCancel="handleCancelPendingBill"
  />

  <!--  意向合同变更  -->
  <PurposeChangeDrawer
      :visible="purposeVisible"
      :id="showType === 'drawer' ? contractId : $route.query.id"
      :disabledTime="[
      contractBasicInfo.lease_starttime,
      contractBasicInfo.lease_endtime,
    ]"
      @cancel="purposeVisible = false"
  />
</template>

<script>
import {
  defineComponent,
  ref,
  watch,
  h,
  computed,
  createVNode,
  onBeforeUnmount,
  onMounted,
  reactive,
  toRefs,
} from "vue";
import {onBeforeRouteLeave, useRoute, useRouter} from "vue-router";
import store from "../../../store";
import BasicInfo from "./BasicInfo.vue";
import ClauseDetail from "./ClauseDetail.vue";
import AnalyzeDetail from "@/views/contract/ContractDetail/AnalyzeDetail.vue";
import CarryForwardList from "@/views/contract/ContractDetail/CarryForwardList.vue";
import ContractHistory from "./ContractHistory.vue";
import IncomeList from "./IncomeList.vue";
import BillInfo from "./BillInfo.vue";
import AttachmentInfo from "../../../components/contract/AttachmentInfo/index.vue";
import request from "../../../common/utils/request";
import {message, Modal} from "ant-design-vue";
import utils from "../../../common/utils/utils";
import RenewalLease from "./modules/RenewalLease.vue";
import {
  ExclamationCircleOutlined,
  DownOutlined,
  ArrowLeftOutlined,
} from "@ant-design/icons-vue";
import AddChange from "./modules/AddChange.vue";
import electronContractModal from "../../../components/ElectronContractModal/index.vue";
import NoHistoryIframe from "@/views/contract/ContractDetail/modules/NoHistoryIframe.vue";
import PendingBillDrawer from "@/views/contract/ContractDetail/modules/PendingBillDrawer.vue";
import PurposeChangeDrawer from "@/views/contract/ContractDetail/modules/PurposeChangeDrawer.vue";
import {TextTip} from "bl-common-vue3";

export default defineComponent({
  name: "contractDetail",
  components: {
    ArrowLeftOutlined,
    BasicInfo,
    ClauseDetail,
    AttachmentInfo,
    ContractHistory,
    IncomeList,
    BillInfo,
    RenewalLease,
    AddChange,
    DownOutlined,
    electronContractModal,
    NoHistoryIframe,
    AnalyzeDetail,
    TextTip,
    CarryForwardList,
    PendingBillDrawer,
    PurposeChangeDrawer,
  },
  props: {
    contractId: {
      type: [Number, String],
      default: "",
    },
    showType: {
      type: String,
      default: "",
    },
    discountType: {
      type: String,
      default: "",
    },
  },
  setup(props, {emit}) {
    const $router = useRouter();
    const $route = useRoute();
    const id =
        props.showType === "drawer"
            ? Number(props.contractId)
            : Number($route.query.id);
    const notBack = $route.query.noBack;
    const goBack = () => {
      if (window.__MICRO_APP_ENVIRONMENT__) {
        const microId = window.microApp?.appName
        window.microApp.forceDispatch({
          type: "SetMicroPagesDel",
          info: {
            microId: microId,
          },
        })
      } else {
        $router.back();
      }
    };

    const iframeVisible = ref(false);
    const iframeUrl = ref("");
    const pendingBillVisible = ref(false);

    const state = reactive({
      purposeVisible: false,
    });
    const iframeModalClose = () => {
      iframeUrl.value = '';
      iframeVisible.value = false;
      basicInfoRefresh.value++;
    };

    const handleCancelPendingBill = () => {
      pendingBillVisible.value = false;
      basicInfoRefresh.value++;
    };

    // 监听返回按钮显示隐藏
    const isMobile = store.getters.isMobile;

    // tab
    const activeTabKey = ref("basicInfo");
    const tabList = ref([]);
    const getTabInfo = () => {
      tabList.value = {
        ...TAB_MAP,
      };
      const {info_label} = contractBasicInfo.value;
      if (info_label.includes("ANALYSIS")) {
        tabList.value.analyzeDetail = {title: "账单分析"};
      }
      if (info_label.includes("BILL")) {
        tabList.value.billInfo = {title: "账单列表"};
      }
      if (info_label.includes("INCOME")) {
        tabList.value.incomeList = {title: "收入列表"};
      }
      if (info_label.includes("TRANSFER")) {
        tabList.value.carryForwardList = {title: "结转列表"};
      }
      if (info_label.includes("LOG")) {
        tabList.value.contractHistory = {title: "合同历史"};
      }
    };

    // 合同基本信息
    const attachParams = ref({});
    const contractBasicInfo = ref({});
    watch(
        () => store.getters.contractDetail,
        (val) => {
          contractBasicInfo.value = val;
          attachParams.value = {
            object_id: val.object_id,
            contract_id: val.id,
          };
          getHeaderInfo(val);
          getTabInfo();
        }
    );

    // 头部信息
    const headerInfo = ref({});
    const getHeaderInfo = (info) => {
      headerInfo.value = {
        pageTitle:
            info.op_type == 4 ? info.proprietor_info.name : info.owner_name,
        abstract: info.latestAbstract,
        statusColor: store.getters.contractStatusColor[info.status],
        statusText: info.status_tips,
        btns: info.operate_button,
        op_type: info.op_type,
        status: info.status,
        is_renewal: info.is_renewal,
        hasChanged: info.hasChanged,
        is_formal: info.is_formal,
      };
      selectValue.value = info.is_renewal == 1 ? "已续租" : selectValue.value;
    };
    const getHeaderMsg = (type) => {
      if (type == "abstract") {
        return `合同摘要：${headerInfo.value[type] || "--"}`;
      }
      if (type == "remark") {
        return `最新备注：${store.getters.latestRemark || "--"}`;
      }
      if (type == "retreat") {
        return `退租摘要: ${store.getters.contractRetreatAbstract || "--"}`;
      }
    };
    // 增加下拉选择
    const selectValue = ref("未续租");
    const selectoptions = ref([
      {
        value: "0",
        label: "未续租",
      },
      {
        value: "1",
        label: "已续租",
      },
      {
        value: "2",
        label: "已退租",
      },
    ]);
    const handleChange = (selectChange) => {
      if (selectChange == 0) {
        return;
      }
      utils.modalConfirm({
        content: "更改后不可修改，请谨慎操作。",
        okType: "danger",
        onOk: () => {
          request
              .get("/org", "/contract/uzhouHandel", {
                contract_id: id,
                handelStatus: selectChange,
              })
              .then((res) => {
                basicInfoRefresh.value++;
              });
        },
        onCancel: () => {
          selectValue.value = "未续租";
        },
      });
    };

    // 删除合同
    const contractDel = () => {
      utils.modalConfirm({
        content: "确定删除本合同吗？",
        okType: "danger",
        onOk: () => {
          request
              .del("/org", "/contract/delete", {
                contract_id: id,
                needMsg: true,
              })
              .then((res) => {
                message.success(res.msg || "删除成功");
                goBack();
              });
        },
      });
    };

    const basicInfoRefresh = ref(0);

    // 下载合同文本
    const downloadFile = () => {
      if (
          contractBasicInfo.value.apply_contract.result.online_preview &&
          contractBasicInfo.value.apply_contract.result.online_preview
              .documentType
      ) {
        contractTitle.value = "在线预览";
        previewUrlData.value = {
          previewUrl:
          contractBasicInfo.value.apply_contract.result.online_preview
              .previewUrl,
          url: contractBasicInfo.value.apply_contract.result.fileUrl,
        };
        esignDetail.value.esignCheck = true;
        electronContractVisible.value = true;
      }
    };

    // 备注
    const showContentInput = ref(false);
    const contentInput = ref("");
    const contentTitle = ref("");
    // 作废追加参数
    const voidOption = reactive({
      option_1: true,
      option_2: true,
    });

    const handleContentSubmit = () => {
      if (!contentInput.value) {
        message.warning(`请输入${contentTitle.value}`);
        return;
      }
      let params = {
        contract_id: id,
        needMsg: true,
      };
      let requestUrl = "";
      if (topBtnType.value == "cancel") {
        requestUrl = "/contract/toVoid";
        params.voidOption = [];
        for (let key in voidOption) {
          if (voidOption[key]) {
            params.voidOption.push(key);
          }
        }
        params.voidReason = JSON.stringify({content: contentInput.value});

        // 如果是意向合同
        if (contractBasicInfo.value.op_type == 5) {
          requestUrl = "/purpose/cancel";
          delete params.voidOption;
        }
      }
      if (topBtnType.value == "revoke") {
        requestUrl = "/contract/toRevoke";
        params.reason = JSON.stringify({content: contentInput.value});
      }

      request.post("/org", requestUrl, params).then((res) => {
        // 更新合同列表
        store.dispatch("SetContractListUpdate", true).then(() => {
          message.success(res.msg || "操作成功！");
          basicInfoRefresh.value++;
          showContentInput.value = false;
        });
      });
    };

    const remarkContentShow = () => {
      contentInput.value = "";
      showContentInput.value = true;
    };

    const changeVisible = ref(false);

    // 页面跳转
    let topBtnType = ref("");
    const elSignLoading = ref(false);
    const renewalVisible = ref(false);
    const esignStampVisible = ref(false);

    // 电子签约
    const electronContractVisible = ref(false);

    const refreshClose = () => {
      electronContractVisible.value = false;
      basicInfoRefresh.value++;
    };

    const closeAllModal = () => {
      emit("closeAllModal");
    };

    const contractTitle = ref("");
    const previewUrlData = ref({});

    const esignDetail = ref({});

    const changeContractVerify = (type) => {
      // 普通合同变更 意向合同变更
      let isChange = type == 'CHANGE';
      request
          .get("/org", "/contract/change/beforeVerify", {
            original_id: id,
          })
          .then((res) => {
            if (isChange) {
              // 普通合同变更
              changeVisible.value = true;
            } else {
              // 意向合同变更
              state.purposeVisible = true;
            }
          })
          .catch((err) => {
            console.log("err", err);
            if (err.code == 10019) {
              Modal.confirm({
                content: () =>
                    err.msg || "当前楼宇合同变更审批流程未设置或被禁用,请设置",
                icon: () => createVNode(ExclamationCircleOutlined),
                centered: true,
                okText: () => "前往",
                onOk() {
                  utils.goProcessContract({type: isChange ? "change" : "purpose_change"});
                  closeAllModal()
                },
              });
            }
          });
    };

    const handleTopBtnClick = (type) => {
      console.log("handleTopBtnClick", type);
      topBtnType.value = type;
      let routeLink = {};
      contractTitle.value = "电子合同";
      previewUrlData.value = {};
      switch (type) {
        case "esign":
          // 获取电子合同设置
          request.get("/org", "/esign/detail", {
            id: contractBasicInfo.value.esign_bucket_id,
            is_check: 1
          }).then((res) => {
            const {detail} = res;
            esignDetail.value = detail;
            esignDetail.value.esignCheck = false;
            if (detail.type == 0) {
              if (contractBasicInfo.value.sign_status == 1) {
                // 签署中
                Modal.info({
                  title: () => "提示",
                  centered: true,
                  content: () =>
                      "您已发起过电子合同签约，请耐心等待签约结果，最终签约结果系统将通过站内通知告知您。",
                });
                return;
              }
              electronContractVisible.value = true;
              return;
            } else {
              // 可以发起签署
              electronContractVisible.value = true;
            }
          }).catch((err) => {
            if (err.code == 50026) {
              Modal.confirm({
                content: () =>
                    err?.msg || '电子合同配置不存在，请前往电子合同中配置',
                icon: () => createVNode(ExclamationCircleOutlined),
                centered: true,
                okText: () => "前往",
                onOk() {
                  $router.push({
                    name: "electronContractList",
                  });
                  closeAllModal();
                },
              });
            }
          });

          break;
        case "esignCheck":
          esignDetail.value.esignCheck = true;
          electronContractVisible.value = true;
          break;
        case "approval":
          if (contractBasicInfo.value.approval_url) {
            iframeUrl.value = contractBasicInfo.value.approval_url;
            iframeVisible.value = true;
          } else {
            if (window.__MICRO_APP_ENVIRONMENT__) {
              window.microApp.forceDispatch({
                type: "SetMicroPages",
                microInfo: {
                  microId: `org_contract_approval`,
                  app: 'org',
                  name: '合同审批',
                  url: `/contract/contractApproval?contractId=${id}&approveId=${contractBasicInfo.value.approve_id}&noBack=1`,
                }
              })
            } else {
              routeLink = {
                name: "contractApproval",
                query: {
                  contractId: id,
                  approveId: contractBasicInfo.value.approve_id,
                },
              };
            }
          }
          break;
        case "cancel":
          // 如果是意向合同
          if (contractBasicInfo.value.op_type == 5) {
            request
                .get("/org", "/purpose/purposeVoidVerify", {
                  contract_id: id,
                })
                .then(() => {
                  contentTitle.value = "作废原因";
                  remarkContentShow();
                });
          } else {
            request
                .get("/org", "/contract/voidBeforeValid", {
                  contract_id: id,
                })
                .then(() => {
                  contentTitle.value = "作废原因";
                  remarkContentShow();
                });
          }

          break;
        case "revoke":
          contentTitle.value = "撤销原因";
          remarkContentShow();
          break;
        case "edit":
          if (window.__MICRO_APP_ENVIRONMENT__) {
            window.microApp.forceDispatch({
              type: "SetMicroPages",
              microInfo: {
                microId: `org_add_contract_${id}`,
                app: 'org',
                name: `创建合同`,
                url: `/contract/addContract?id=${id}`,
              }
            })
          }
          break;
        case "retreat":
          request
              .get("/org", "/retreat/beforeVerify", {
                contract_id: id,
                owner_id: contractBasicInfo.value.owner_id,
              })
              .then((res) => {
                if (window.__MICRO_APP_ENVIRONMENT__) {
                  window.microApp.forceDispatch({
                    type: "SetMicroPages",
                    microInfo: {
                      microId: `org_add_retreat`,
                      app: 'org',
                      name: `退租协议`,
                      url: `/bill/addRetreat?id=${id}&owner_id=${contractBasicInfo.value.owner_id}&type=edit&noBack=1`,
                    }
                  })
                }
                closeAllModal();
              })
              .catch((err) => {
                console.log("err", err);
                if (err.code == 50026) {
                  Modal.confirm({
                    content: () =>
                        "当前楼宇合同退租审批流程未设置或被禁用,请设置",
                    icon: () => createVNode(ExclamationCircleOutlined),
                    centered: true,
                    okText: () => "前往",
                    onOk() {
                      utils.goProcessContract({type: "retreat"});
                      closeAllModal();
                    },
                  });
                }
                if (err.code == 50027) {
                  Modal.confirm({
                    content: () =>
                        "该租客的账单有滞纳金未结清，为防止滞纳金漏缴，请在退租前结算滞纳金",
                    icon: () => createVNode(ExclamationCircleOutlined),
                    centered: true,
                    okText: () => "确定",
                    cancelButtonProps: {style: {display: "none"}},
                  });
                }
                if (err.code == 50028) {
                  Modal.confirm({
                    content: () => "该合同下账单正处于审批中，请稍后进行退租操作",
                    icon: () => createVNode(ExclamationCircleOutlined),
                    centered: true,
                    okText: () => "确定",
                    cancelButtonProps: {style: {display: "none"}},
                  });
                }
              });
          break;
        case "retreatHistory":
          if (window.__MICRO_APP_ENVIRONMENT__) {
            window.microApp.forceDispatch({
              type: "SetMicroPages",
              microInfo: {
                microId: `org_add_retreat`,
                app: 'org',
                name: `退租协议`,
                url: `/bill/addRetreat?id=${id}&owner_id=${contractBasicInfo.value.owner_id}&type=view&noBack=1`,
              }
            })
          }
          closeAllModal();
          break;
        case "continue":
          request
              .get("/org", "/continue/beforeVerify", {
                contract_id: id,
              })
              .then(() => {
                renewalVisible.value = true;
              })
              .catch((err) => {
                console.log("err", err);
                if (err.code == 50067) {
                  Modal.confirm({
                    title: () => "提示",
                    content: () => "您需要先添加合同续租审批流程才能续租合同哦~",
                    icon: () => createVNode(ExclamationCircleOutlined),
                    centered: true,
                    okText: () => "前往",
                    onOk() {
                      utils.goProcessContract({type: "continue"});
                      closeAllModal();
                    },
                  });
                }
              });
          break;
        case "change":
          request
              .get("/org", "/contract/change/beforeVerify", {
                original_id: id,
              })
              .then((res) => {
                changeVisible.value = true;
              })
              .catch((err) => {
                console.log("err", err);
                if (err.code == 10019) {
                  Modal.confirm({
                    content: () =>
                        err.msg || "当前楼宇合同变更审批流程未设置或被禁用,请设置",
                    icon: () => createVNode(ExclamationCircleOutlined),
                    centered: true,
                    okText: () => "前往",
                    onOk() {
                      utils.goProcessContract({type: "change"});
                      closeAllModal();
                    },
                  });
                }
              });
          break;
        case "LOOK_NEW":
          if (
              contractBasicInfo.value.changeData &&
              contractBasicInfo.value.changeData.change_content &&
              contractBasicInfo.value.changeData.change_content.contract_id
          ) {
            if (window.__MICRO_APP_ENVIRONMENT__) {
              window.microApp.forceDispatch({
                type: "SetMicroPages",
                microInfo: {
                  microId: `org_contract_detail`,
                  app: 'org',
                  name: `合同详情`,
                  url: `/contract/contractDetail?id=${contractBasicInfo.value.changeData.change_content.contract_id}&notBack=1`,
                }
              })
            }else{
              $router.push({
                  name: "contractDetail",
                  query: {
                    id:contractBasicInfo.value.changeData.change_content.contract_id
                  },
                });
            }
          }

          break;
        case "CHANGE_FORMAL":
          if (window.__MICRO_APP_ENVIRONMENT__) {
            window.microApp.forceDispatch({
              type: "SetMicroPages",
              microInfo: {
                microId: `org_add_contract_${id}_transferNormal`,
                app: 'org',
                name: `创建合同`,
                url: `/contract/addContract?id=${id}&editType=transferNormal`,
              }
            })
          }
          break;
        case "TRANSFER":
          // 结转
          request
              .get("/org", "/billTransfer/beforeVerify", {
                id,
              })
              .then((res) => {
                if (window.__MICRO_APP_ENVIRONMENT__) {
                  window.microApp.forceDispatch({
                    type: "SetMicroPages",
                    microInfo: {
                      microId: `org_contract_carry_over`,
                      app: 'org',
                      name: `合同结转`,
                      url: `/contract/contractCarryOver?id=${id}&notBack=1`,
                    }
                  })
                }else{
                  $router.push({
                      name: "contractCarryOver",
                      query: {
                        id,
                      },
                    });
                }
               
              })
          break;
        case "ONHANDLEBILL":
          // 查看待处理账单
          pendingBillVisible.value = true;
          break;
        case "PURPOSE_CHANGE":
          // 意向合同变更
          changeContractVerify("PURPOSE_CHANGE");
          break;
        case "PURPOSE_EDIT":
          // 意向合同编辑
          if (window.__MICRO_APP_ENVIRONMENT__) {
            window.microApp.forceDispatch({
              type: "SetMicroPages",
              microInfo: {
                microId: `org_add_contract_${id}_purposeContractEdit`,
                app: 'org',
                name: `创建合同`,
                url: `/contract/addContract?contractType=purposeContractEdit&id=${id}`,
              }
            })
          }
          break;
        default:
          break;
      }

      if (routeLink.name) {
        $router.push(routeLink);
        closeAllModal();
      }
    };

    const handleMenuClick = ({key}) => {
      switch (key) {
        case "CHANGE":
          changeContractVerify("CHANGE");
          break;
        case "COPY":
          if (window.__MICRO_APP_ENVIRONMENT__) {
            window.microApp.forceDispatch({
              type: "SetMicroPages",
              microInfo: {
                microId: `org_add_contract_${id}_copy`,
                app: 'org',
                name: `创建合同`,
                url: `/contract/addContract?id=${id}&contractEditType=copy`,
              }
            })
          }
          closeAllModal()
          break;
        default:
          break;
      }
    };

    const init = (initTab = false) => {
      const routeTab = $route.query.tab;
      if (routeTab) {
        activeTabKey.value = routeTab;
      } else {
        activeTabKey.value = initTab
            ? "basicInfo"
            : store.getters.lastActiveTab;
      }
    };

    onBeforeRouteLeave((to) => {
      attachParams.value = {};
      if (["contractList", "contractFile", "contractDraft"].includes(to.name)) {
        store.dispatch("SetLastActiveTab");
      } else {
        store.dispatch("SetLastActiveTab", activeTabKey.value);
      }
    });

    onMounted(() => {
      init(true);
    });

    watch(
        [() => $route.query.id, () => $route.name],
        ([id, name], [preId, preName]) => {
          if (id != preId) {
            basicInfoRefresh.value++;
            init(name == preName);
          }
        }
    );

    watch(
        () => props.contractId,
        (val, preVal) => {
          if (val != preVal && props.showType === "drawer") {
            basicInfoRefresh.value++;
            init(true);
          }
        }
    );

    // const esignStampSuccess = (sign_type) => {
    //   esignStampVisible.value = false;
    //   elSignLoading.value = true;
    //   let params = {
    //     contract_id: id,
    //   };
    //   if (sign_type) {
    //     params.sign_type = sign_type;
    //   }
    //   request
    //     .get("/org", "/esign/uploadContract", params)
    //     .then((res) => {
    //       Modal.info({
    //         title: () => "提示",
    //         centered: true,
    //         content: () =>
    //           h("div", [
    //             h(
    //               "p",
    //               "电子合同签约发起成功！签约短信已下发到租客手机，请提醒租客点击短信进行签约。"
    //             ),
    //             h("p", "最终签约结果系统将通过站内通知告知您。"),
    //           ]),
    //       });
    //     })
    //     .finally(() => {
    //       elSignLoading.value = false;
    //       basicInfoRefresh.value++;
    //     });
    // };

    return {
      ...toRefs(state),
      tabList,
      activeTabKey,
      headerInfo,
      attachParams,
      showContentInput,
      contentInput,
      contentTitle,
      basicInfoRefresh,
      contractBasicInfo,
      elSignLoading,
      notBack,
      goBack,
      getHeaderMsg,
      contractDel,
      handleTopBtnClick,
      handleContentSubmit,
      downloadFile,
      isMobile,
      selectoptions,
      selectValue,
      handleChange,
      renewalVisible,

      changeVisible,
      handleMenuClick,
      esignStampVisible,
      topBtnType,
      voidOption,

      electronContractVisible,
      refreshClose,
      esignDetail,
      contractTitle,
      previewUrlData,
      closeAllModal,
      iframeModalClose,
      iframeVisible,
      iframeUrl,
      pendingBillVisible,
      handleCancelPendingBill,
    };
  },
});

const TAB_MAP = {
  basicInfo: {title: "合同信息"},
  clauseDetail: {title: "合同明细"},
  // analyzeDetail: { title: "账单分析" },
  contractText: {title: "合同文本"},
  // billInfo: { title: "账单列表" },
  //   basicInfo: { title: "结转列表" },
  // incomeList: { title: "收入列表" },
  //   basicInfo: { title: "凭证列表" },
  // contractHistory: { title: "合同历史" },
};
</script>

<style lang="less" scoped>
.contract-detail {
  height: 100%;
  display: flex;
  flex-direction: column;

  &.isMobile {
    :deep(.ant-page-header-back) {
      display: none;
    }
  }

  .header {
    background: #fff;
    // height: 210px;
    overflow: auto;
    margin-left: 1px;
    border-bottom: 1px solid #f0f2f5;

    &:deep(.ant-page-header) {
      padding: 10px 20px 0 20px;
    }
  }

  .content {
    flex: 1;
    width: 100%;
    //max-height: calc(100% - 210px);
    padding: 10px;
    box-sizing: border-box;
    overflow-y: auto;
    overflow-x: auto;
  }
}

.el-loading {
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  z-index: 1000;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.6);
}

.hide-back {
  :deep(.ant-page-header-back) {
    display: none;
  }
}
</style>
